﻿using Newtonsoft.Json;
using up6.db.model;
using up6.utils;

namespace Up6.core.Up6Manager.Biz;

/// <summary>
/// 文件夹层级结构类
/// 用法：
/// FolderSchema fs = new FolderSchema();
/// fs.create();//在文件夹初始化时创建
/// fs.addFile();//在上传第一块子文件数据时添加信息。
/// 更新记录：
///     2020-11-18 创建
/// </summary>
public class FolderSchema
{
    /// <summary>
    /// 创建结构文件
    /// pathSvr/scheme.txt
    /// </summary>
    /// <param name="dir"></param>
    public bool create(FileInf dir)
    {
        String file = dir.schemaFile();
        var val = JsonConvert.SerializeObject(dir);
        File.WriteAllText(file, val + "\n");
        return File.Exists(file);
    }

    /// <summary>
    /// 添加一条记录
    /// </summary>
    /// <param name="f"></param>
    public void addFile(FileInf f)
    {
        //统一路径格式
        var root = f.pathSvr.Replace("\\","/");
        if (!string.IsNullOrEmpty(f.pathRel)) root = root.Replace(f.pathRel, "");

        //guid/Soft/folder1/QQ.exe->/guid/Soft
        root = Path.GetDirectoryName(root);
        //guid/
        root = Path.GetDirectoryName(root);
        var file = Path.Combine(root, "schema.txt");
        f.pathLoc = f.pathLoc.Replace("\\", "/");
        f.pathRel = f.pathRel.Replace("\\", "/");
        f.pathSvr = f.pathSvr.Replace("\\", "/");
        var val = JsonConvert.SerializeObject(f);
        if (File.Exists(file)) FileTool.appendSafe(file, val + "\n");
    }
}